<template>
    <div style="position: absolute;width:200px;height:30px;top:86px;left: calc(100vw - 200px);z-index: 999">
        <el-link style="float: left;line-height: 30px;margin-right: 5px" type="success" title="排队数量">0</el-link>
        <el-button-group  style="display: inline" >
            <el-button type="success" v-if="!state.signIn" @click="signIn">签入</el-button>
            <el-button type="success" v-if="state.signIn" @click="signOut">签出</el-button>
            <el-button type="success" @click="ready" :disabled="!state.ready">就绪</el-button>
            <el-button type="success" @click="rest" :disabled="!state.rest">小休</el-button>
         </el-button-group>
    </div>
    <el-row>
        <el-col :span="24">
            <el-tabs type="border-card" closable @tab-remove="tabRemove" @tab-click="tabClick" v-model="currentChat.name" class="demo-tabs">
                <el-tab-pane v-for="chat in chats" :key="chat.id" :name="chat.clientName" >
                    <template #label>
                        <span class="custom-tabs-label">
                                <span>
                                    {{chat.clientName}}
                                </span>
                              <el-badge v-if="chat.unreadCount > 0" class="mark" style="margin-left:5px" :value="chat.unreadCount" />
                        </span>
                    </template>
                    <el-row>
                    <el-col :span="12">
                    <div>
                        <!--消息框-->
                        <div class ="scrollDiv" ref="msgBoxs" :title="chat.clientName" style="height:calc(100vh - 340px); overflow:auto; border: 1px solid #ccc;
                        border-radius: 5px;background-color: #f5f5f5;">
                            <div v-for="(msg, idx) in chat.msgs">
                                <!--//左边显示的消息消息-->
                                <div v-if="msg.sender == 'client'" class="el-row" style="padding: 5px 0">
                                    <div class="el-col el-col-2" style="text-align: right">
                                      <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">
                                        <img src="@/assets/client-icon.png" style="object-fit: cover;">
                                      </span>
                                    </div>
                                    <div class="el-col el-col-22" style="text-align: left; padding-left: 10px ">
                                        <div class="tip left">{{msg.content}}</div>
                                        <div class="time">{{moment(msg.createTime).format("yyyy-MM-DD HH:mm:ss")}}</div>
                                    </div>
                                </div>
                                <!--边显示的消息-->
                                <div v-if="msg.sender == 'agent'" class="el-row" style="padding: 5px 0">
                                    <div class="el-col el-col-22" style="text-align: right; padding-right: 10px">
                                        <div class="time">{{moment(msg.createTime).format("yyyy-MM-DD HH:mm:ss")}}</div>
                                        <div class="tip right">{{msg.content}}</div>
                                    </div>
                                    <div class="el-col el-col-2">
                                     <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">
                                        <img src="@/assets/agent-icon.png" style="object-fit: cover;">
                                     </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!--消息框结束-->
                        <div style="height:20px;border:none;">
                        </div><!--输入框结束-->
                        <!--输入框-->
                        <div style="height: 120px;border-radius: 5px;border:1px solid #ccc;">
                            <textarea @keydown.enter.prevent="send(chat)" style="height: 100%; width: 100%; padding-top: 10px;
                             outline: none;border: none; resize: none" v-model="chat.inputBox" />
                        </div><!--输入框结束-->
                        <el-button style="margin-top:10px;float:right" type="primary"  @click="send(chat)">发送</el-button>
                    </div>
                    </el-col>
                    <el-col :span="12" style="padding:0 5px">
                        <el-tabs  style="height: 100%" type="border-card" >
                            <el-tab-pane label="服务单"><ServiceTicket :chatId="chat.id" :clientId="chat.clientId" type="edit"/></el-tab-pane>
                            <el-tab-pane label="历史记录">历史会话记录。。。</el-tab-pane>
                        </el-tabs>
                    </el-col>
                    </el-row>
                </el-tab-pane>
            </el-tabs>
        </el-col>

    </el-row>
</template>

<script setup>
    import {ElMessage} from 'element-plus'
    import {nextTick, onMounted, reactive, ref,onUnmounted} from 'vue'
    import ServiceTicket from '@/components/business/ServiceTicket.vue'
    import moment from 'moment'
    import request from '@/utils/request.js'
    let currentChat = reactive({name:null})
    const msgBoxs = ref([])
    let chats = reactive([])
    let keepalive = null
    let websocket = null
    let msgMap = new Map()

    let state = reactive({signIn:false, ready:false, rest:false})
        let userdb = JSON.parse(sessionStorage.getItem("user")||"{}")

        websocket  = new WebSocket("ws://localhost:9080/online/agent/"+userdb.id)

        websocket.onerror = function (e) {
            ElMessage({message: "websocket连接出错", type: 'error'})
        }
        websocket.onmessage = function (event) {
            let msg = JSON.parse(event.data);
            let chat = null
            for(let i=0; i < chats.length; i++){
                if(chats[i].clientName === msg.clientName){
                    chat = chats[i]
                    break
                }
            }
            if(chat == null){
                chat = {
                    id:msg.chatId,
                    clientName:msg.clientName,
                    clientId:msg.clientId,
                    unreadCount:1,
                    msgs:[msg]
                }
                chats.push(chat)
            }else{
                chat.msgs.push(msg)
                if(msg.sender!="agent"){
                    if(currentChat.name != chat.clientName){
                        chat.unreadCount++
                    }
                }
            }
            if(chats.length == 1){
                currentChat.name = msg.clientName
                chat.unreadCount = 0
            }
            scrollerToBottom(chat.clientName)
        }
    onMounted(function () {
        keepalive = setInterval(function(){
            request.get(`/api/keepalive`).then(resp => {
             })
            },
          30*1000)
    })
    onUnmounted(function () {
        websocket.close()
        clearInterval(keepalive)
    })

    function send(chat){

        let content = chat.inputBox.trim()
        if(content===""){
            ElMessage({message: "请输入内容",type: 'error'})
            return
        }
        let msg = {"sender" : "agent", "content" : content,"type" : "text","chatId" : chat.id,"clientName" : currentChat.name}
        // chat.msgs.push(msg)
        websocket.send(JSON.stringify(msg))
        chat.inputBox = ""
        scrollerToBottom(chat.clientName)
    }

    function tabRemove(clientName){
        let index = null;
        for(let i=0; i < chats.length; i++){
            if(chats[i].clientName === clientName){
                index = i
                break
            }
        }
        if(index != null){
            chats.splice(index)
        }
    }

    function tabClick(tab, event){
        let chat = null
        currentChat.name = tab.props.name
        for(let i=0; i < chats.length; i++){
            if(chats[i].clientName === tab.props.name){
                chat = chats[i]
                break
            }
        }
        chat.unreadCount = 0
    }

    function scrollerToBottom(clientName) {
        let areas = msgBoxs.value
        let thisArea = null
        for (let i=0;i<areas.length;i++){
            let temp = areas[i]
            if(temp.title === clientName){
                thisArea = temp
                break
            }
        }
        nextTick(() => {
            if(thisArea !== null){
                thisArea.scrollTop = thisArea.scrollHeight
            }

        });
    }
    function signIn(){
        request.get(`/api/online/signIn`).then(resp => {
            state.signIn = true
           state.ready = true
           state.rest = false
        })
    }
    function signOut(){
        request.get(`/api/online/signOut`).then(resp => {
            state.ready = false
            state.rest = false
            state.signIn = false
        })
    }
    function ready(){
        request.get(`/api/online/ready`).then(resp => {
            state.ready = false
            state.rest = true
        })
    }
    function rest(){
        request.get(`/api/online/rest`).then(resp => {
            state.ready = true
            state.rest = false
        })
    }
</script>
<style lang="css">
    .tip {
        border-radius: 10px;
        padding: 10px;
        width:auto;
        display:inline-block;
        word-wrap: break-word;
        word-break: break-all;
        text-align:left;
        max-width:60%;
    }
    .time {
        padding: 5px;
        display:inline-block;
        color: #8f9093;
        font-size: 13px;
    }
    .item {
        margin-top: 5px;
    }
    .right {
        background-color: #84db49;
    }
    .left {
        background-color:  white;
    }
    .span-box {
        display: flex;
        justify-content: flex-start;
        align-items: center;}
    .btn-bell-badge {
        width: 26px;
        height: 18px;
        margin-left:5px;
        line-height:18px;
        border-radius: 15px;
        background: #f56c6c;}
    .num {
        display: block;
        width: 100%;
        text-align: center;
        font-size: 12px;
        color: #fff;
    }
</style>